import { useEffect, useState } from 'react'

export function useLocalStorage<T>(key: string, defaultValue: T | (() => T)) {
  const [data, setData] = useState<T>(() => {
    const v = window.api.getItem(key)
    if (v && typeof v === 'string') {
      return JSON.parse(v)
    }
    if (typeof defaultValue === 'function') {
      return (defaultValue as () => T)()
    }
    return defaultValue
  })
  useEffect(() => {
    window.api.setItem(key, JSON.stringify(data))
  }, [key, data])
  return [data, setData] as const
}
